package com.zxd.interview.eightthread.threadobjectclasscommonmethod;

/**
 * 释放多个锁
 *
 * @author Xander
 * @version v1.0.0
 * @Package : com.zxd.interview.eightthread.threadobjectclasscommonmethod
 * @Description : 释放多个锁
 * @Create on : 2023/3/12 14:25
 **/
public class ReleaseMultipleLocks {

    private static volatile Object object1 = new Object();
    private static volatile Object object2 = new Object();

    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            synchronized (object1) {
                System.out.println(Thread.currentThread().getName() + "获取到锁 object1");
                synchronized (object2) {
                    System.out.println(Thread.currentThread().getName()+ "获取到锁 object2");
                    try {
                        System.out.println(Thread.currentThread().getName() + "释放锁A");
                        object1.wait();
                        // 锁B也要一起释放，但是此时线程B已然回等待
                        System.out.println(Thread.currentThread().getName() + "释放锁B");
                        object2.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + "释放锁B");
            }

        });
        thread.setName("线程A");
        thread.start();

        Thread thread2 = new Thread(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (object1) {
                System.out.println(Thread.currentThread().getName() + "获取到锁 object1");

                System.out.println(Thread.currentThread().getName() + "尝试获取到锁 object2");
                synchronized (object2) {
                    System.out.println(Thread.currentThread().getName() + "获取到锁 object2");
                }
            }
        });
        thread2.setName("线程B");
        thread2.start();
    }/**
     运行结果：

     发现线程B一直等待线程A释放锁B，wait释放的只有锁A，锁B没有被释放

     线程A获取到锁 object1
     线程A获取到锁 object2
     线程B获取到锁 object1
     */




}
